package com.tarena.lbs.user.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.dao.repository.AdminRepository;
import com.tarena.lbs.user.dao.repository.UserGroupRepository;
import com.tarena.lbs.user.pojo.po.AdminPO;
import com.tarena.lbs.user.pojo.po.UserGroupPO;
import com.tarena.lbs.user.pojo.param.UserGroupParam;
import com.tarena.lbs.user.pojo.query.UserGroupQuery;
import com.tarena.lbs.user.pojo.vo.UserGroupVO;
import com.tarena.lbs.user.service.UserGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserGroupServiceImpl implements UserGroupService {

    @Autowired
    private UserGroupRepository userGroupRepository;

    @Autowired
    private AdminRepository adminRepository;

    @Override
    public PageResult<UserGroupVO> pageList(UserGroupQuery query) throws BusinessException {
        // 1. 验证用户信息（从ThreadLocal获取用户id）
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null, new BusinessException("-1", "用户认证解析失败"));
        Integer userId = userPrinciple.getId();

        // 2. 通过用户id获取用户信息（判断用户数据是否存在）
        AdminPO adminPO = adminRepository.getAdminById(userId);
        Asserts.isTrue(adminPO == null, new BusinessException("-2", "用户信息不存在"));

        // 3. 得到商家id
        Integer businessId = adminPO.getBusinessId();
        Asserts.isTrue(businessId == null, new BusinessException("-3", "用户未关联商家"));

        // 4. 通过商家id获取用户分组列表
        query.setBusinessId(businessId);
        PageInfo<UserGroupPO> pageInfo = userGroupRepository.pageList(query);

        // 5. 转换为VO并返回
        PageResult<UserGroupVO> voPage = new PageResult<>();
        voPage.setPageNo(pageInfo.getPageNum());
        voPage.setPageSize(pageInfo.getPageSize());
        voPage.setTotal(pageInfo.getTotal());

        List<UserGroupVO> vos = null;
        List<UserGroupPO> pos = pageInfo.getList();
        if (CollectionUtils.isNotEmpty(pos)) {
            vos = pos.stream().map(po -> {
                UserGroupVO vo = new UserGroupVO();
                BeanUtils.copyProperties(po, vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPage.setObjects(vos);
        return voPage;
    }

    @Override
    public void save(UserGroupParam param) throws BusinessException {
        // 1. 验证用户信息（从ThreadLocal获取用户id）
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null, new BusinessException("-1", "用户认证解析失败"));
        Integer userId = userPrinciple.getId();

        // 2. 通过用户id获取用户信息（判断用户数据是否存在）
        AdminPO adminPO = adminRepository.getAdminById(userId);
        Asserts.isTrue(adminPO == null, new BusinessException("-2", "用户信息不存在"));

        // 3. 得到商家id
        Integer businessId = adminPO.getBusinessId();
        Asserts.isTrue(businessId == null, new BusinessException("-3", "用户未关联商家"));

        // 4. 保存分组数据
        UserGroupPO userGroupPO = new UserGroupPO();
        BeanUtils.copyProperties(param, userGroupPO);
        userGroupPO.setBusinessId(businessId);
        userGroupPO.setCreateAt(new Date());

        userGroupRepository.save(userGroupPO);
        log.info("用户分组保存成功，分组名称：{}，商家ID：{}", param.getGroupName(), businessId);
    }
}
